﻿
Public Class WinCcDataSorter
    Private data As Hashtable
    Private cols As ArrayList
    Private rowtemplate As Hashtable
    Private isready As Boolean = False
    Public Sub New()
        data = New Hashtable
        cols = New ArrayList
    End Sub
    Public Sub addCol(ByVal col As WcTagValue)
        cols.Add(col)
    End Sub
    Private Sub prepare()
        rowtemplate = New Hashtable
        rowtemplate.Add("datetime", Nothing)
        For Each r As WcTagValue In cols
            rowtemplate.Add(r.ValueName, Nothing)
        Next
        isready = True
    End Sub
    Public Function addValue(ByVal dtm As DateTime, ByVal valuename As String, ByVal value As Double) As Boolean
        dtm = commons.toDate(dtm)
        If (Not isready) Then prepare()
        Dim nr As Hashtable = getRow(dtm)
        If (IsNothing(nr)) Then
            nr = rowtemplate.Clone
            nr.Item("datetime") = dtm
            nr.Item(valuename) = value
            data.Add(dtm, nr)
            Return True
        End If
        nr.Item(valuename) = value
        'data.Item(dtm) = nr
        Return True
    End Function

    Public Function setvalue(ByVal dt As ewindt.DtProcessValueDataTable) As Boolean
        If (IsNothing(dt)) Then Return False
        For Each r As ewindt.DtProcessValueRow In dt.Rows
            Dim col As WcTagValue = getColById(r.ValueID)
            If (Not IsNothing(col)) Then
                addValue(r.TimeStamp, col.ValueName, r.RealValue)
            End If
        Next
        Return True
    End Function
    Private Function getColById(ByVal id As Integer) As WcTagValue
        For Each col As WcTagValue In Me.cols
            If (col.ValueId = id) Then Return col
        Next
        Return Nothing
    End Function
    Private Function getRow(ByVal key As DateTime) As Hashtable
        For Each dk As DateTime In data.Keys
            Dim ea As Integer = System.DateTime.Compare(dk, key)
            If (ea = 0) Then Return data.Item(dk)
        Next
        'If (data.ContainsKey(key)) Then Return data.Item(key)
        'Dim h = data.Item(key)
        Return Nothing
    End Function
    Public Function getData() As Hashtable
        Return data
    End Function
End Class
